
package com.tools.cleanmaster.store;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.text.TextUtils;

import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;
import com.tools.cleanmaster.utils.PackageUtils;

public class CandySaverSharedPrefManager {

    private static final boolean DEBUG = FeatureConfig.DEBUG_LOG;
    public static final String TAG = "CandySaverSharedPrefManager";

    private static final String PREFS_FILE = "screen_saver_sp_date";
    private static final String LOCKSCREEN_RECOMMEND_SWITCH = "recommend_switch"; // 屏保推荐功能开关
    private static final String LOCKSCREEN_RECOMMEND_NEW_PROTECT_TIME = "recommend_new_pro_time"; // 新用户保护时间
    private static final String LOCKSCREEN_RECOMMEND_SHOW_TIMES = "recommend_show_times"; // 屏保推荐功能展示次数
    private static final String LOCKSCREEN_RECOMMEND_INTER_TIME = "recommend_int_time"; // 屏保推荐功能间隔展示时间
    private static final String LOCKSCREEN_RECOMMEND_HAS_SHOWTIMES = "recommend_has_show_times"; // 屏保推荐功能间隔展示时间
    private static final String LOCKSCREEN_RECOMMEND_SHOW_NOWTIME = "recommend_show_nowtime"; // 屏保推荐功能间隔展示时间

    private static final String SCREEN_SWITCH_CONFIG = "switch_config";
    private static final String SP_SCREEN_STRATEGY = "screen_strategy";
    private static final String SP_SCREEN_FBID = "screen_fbid";

    private static final String SP_BATTERY_FILE_NAME = "battery_global_configs_sp";
    private static final String SP_BOOSTER_FILE_NAME = "charging_global_configs_sp";
    private static final String KEY_LOCK_SCREEN_GUIDE = "lock_screen_guide";


    private static CandySaverSharedPrefManager sDataMgr = null;
    private Context mContext;
    private SharedPreferences mSharedPreferences;

    public static CandySaverSharedPrefManager getInstance(Context ctx) {
        if (sDataMgr == null) {
            synchronized (CandySaverSharedPrefManager.class) {
                if (sDataMgr == null) {
                    sDataMgr = new CandySaverSharedPrefManager(ctx);
                }
            }
        }
        return sDataMgr;
    }

    private CandySaverSharedPrefManager(Context ctx) {
        mContext = ctx.getApplicationContext();
    }

    public void registerDataPipe() {
//        ThreadPool.runOnPool(new Runnable() {
//            @Override
//            public void run() {
//                NotifyManager.registDataPipe(DataPipeIDConfig.DATA_PIPE, CandySaverSharedPrefManager.this);
//                NotifyManager.getDataPipeData(DataPipeIDConfig.DATA_PIPE, CandySaverSharedPrefManager.this);
//                NotifyManager.registDataPipe(DataPipeIDConfig.SCREEN_STATUS_PIPE, CandySaverSharedPrefManager.this);
//                NotifyManager.getDataPipeData(DataPipeIDConfig.SCREEN_STATUS_PIPE, CandySaverSharedPrefManager.this);
//                NotifyManager.registDataPipe(DataPipeIDConfig.SCREEN_AD_STRATEGY_PIPE, CandySaverSharedPrefManager.this);
//                NotifyManager.getDataPipeData(DataPipeIDConfig.SCREEN_AD_STRATEGY_PIPE, CandySaverSharedPrefManager.this);
//                NotifyManager.registDataPipe(DataPipeIDConfig.SCREEN_FACEBOOK_HOOK_PIPE, CandySaverSharedPrefManager.this);
//                NotifyManager.getDataPipeData(DataPipeIDConfig.SCREEN_FACEBOOK_HOOK_PIPE, CandySaverSharedPrefManager.this);
//                NotifyManager.registDataPipe(DataPipeIDConfig.SCREEN_SAVER_AD_CONTROLL, CandySaverSharedPrefManager.this);
//                NotifyManager.getDataPipeData(DataPipeIDConfig.SCREEN_SAVER_AD_CONTROLL, CandySaverSharedPrefManager.this);
//
//            }
//        });
    }

    public void checkLockScreenCloudSwitch() {
        String body = getSwitchConfigData();
        if (body == null || body.isEmpty()) {
            return;
        }
        if (DEBUG) {
            LogHelper.d(TAG, "云端屏保开关配置开始检查：" + body);
        }
        if (isLockScreenPure()) {
            boolean screenSaverSwitch = CloudSwitchSharedPrefManager.getCloudSwitch(body);
            if (screenSaverSwitch) {
                //MakingManager.getInstance(mContext).setInactiveOpen();
            }
            if (DEBUG) {
                LogHelper.d(TAG, "云端配置开关为：" + screenSaverSwitch + "没有手动操作过" + isLockScreenPure());
            }
        } else {
            if (DEBUG) {
                LogHelper.d(TAG, "手动操作过");
            }
        }
    }


    public void setRecommendSwitch(boolean on) {
        SharedPreferences configs = getSharedPreferences();
        SharedPreferences.Editor edit = configs.edit();
        edit.putBoolean(LOCKSCREEN_RECOMMEND_SWITCH, on);
        edit.apply();
    }

    public boolean getRecommendSwitch() {
        SharedPreferences configs = getSharedPreferences();
        boolean dftSwitch = RecommendConfigs.DEFAULT_RECOMMEND_SWITCH;
        return configs.getBoolean(LOCKSCREEN_RECOMMEND_SWITCH, dftSwitch);
    }

    public void setRecommendNewProTime(long time) {
        SharedPreferences configs = getSharedPreferences();
        SharedPreferences.Editor edit = configs.edit();
        edit.putLong(LOCKSCREEN_RECOMMEND_NEW_PROTECT_TIME, time);
        edit.apply();
    }

    public long getRecommendNewProTime() {
        SharedPreferences configs = getSharedPreferences();
        long dftTime = RecommendConfigs.DEFAULE_RECOMMEND_NEW_PROTECT_TIME;
        return configs.getLong(LOCKSCREEN_RECOMMEND_NEW_PROTECT_TIME, dftTime);
    }

    public void setRecommendIntTime(long time) {
        SharedPreferences configs = getSharedPreferences();
        SharedPreferences.Editor edit = configs.edit();
        edit.putLong(LOCKSCREEN_RECOMMEND_INTER_TIME, time);
        edit.apply();
    }

    public long getRecommendIntTime() {
        SharedPreferences configs = getSharedPreferences();
        long dftTime = RecommendConfigs.DEFAULE_RECOMMEND_INTER_TIME;
        return configs.getLong(LOCKSCREEN_RECOMMEND_INTER_TIME, dftTime);
    }

    public void setRecommendTimes(int time) {
        SharedPreferences configs = getSharedPreferences();
        SharedPreferences.Editor edit = configs.edit();
        edit.putInt(LOCKSCREEN_RECOMMEND_SHOW_TIMES, time);
        edit.apply();
    }

    public int getRecommendTimes() {
        SharedPreferences configs = getSharedPreferences();
        int dftTimes = RecommendConfigs.DEFAULT_RECOMMEND_SHOW_TIMES;
        return configs.getInt(LOCKSCREEN_RECOMMEND_SHOW_TIMES, dftTimes);
    }

    public void setRecommendHasShowTimes(int time) {
        SharedPreferences configs = getSharedPreferences();
        SharedPreferences.Editor edit = configs.edit();
        edit.putInt(LOCKSCREEN_RECOMMEND_HAS_SHOWTIMES, time);
        edit.apply();
    }

    public int getRecommendHasShowTimes() {
        SharedPreferences configs = getSharedPreferences();
        return configs.getInt(LOCKSCREEN_RECOMMEND_HAS_SHOWTIMES, 0);
    }

    public void setRecommendShowNowTime(long time) {
        SharedPreferences configs = getSharedPreferences();
        SharedPreferences.Editor edit = configs.edit();
        edit.putLong(LOCKSCREEN_RECOMMEND_SHOW_NOWTIME, time);
        edit.apply();
    }

    public long getRecommendShowNowTime() {
        SharedPreferences configs = getSharedPreferences();
        return configs.getLong(LOCKSCREEN_RECOMMEND_SHOW_NOWTIME, 0);
    }

    private SharedPreferences getSharedPreferences() {
        if (mSharedPreferences == null) {
            synchronized (this) {
                if (mSharedPreferences == null) {
                    mSharedPreferences = mContext.getSharedPreferences(PREFS_FILE,
                            Context.MODE_PRIVATE);
                }
            }
        }
        return mSharedPreferences;
    }

    /*public boolean getBatteryLockScreenGuideShow() {
        String pkgName = DX_BATTERY_PACKAGENAME;
        String fileName = CandySaverSharedPrefManager.SP_BATTERY_FILE_NAME;
        SharedPreferences batteryConfigs = getPackageSharedPreferences(mContext, pkgName, fileName);
        if (batteryConfigs == null) {
            return false;
        }
        return batteryConfigs.getBoolean(KEY_LOCK_SCREEN_GUIDE, false);
    }*/

    /*public boolean getBoosterLockScreenGuideShow() {
        String pkgName = DX_BOOSTER_PACKAGENAME;
        String fileName = CandySaverSharedPrefManager.SP_BOOSTER_FILE_NAME;
        SharedPreferences boosterConfigs = getPackageSharedPreferences(mContext, pkgName, fileName);
        if (boosterConfigs == null) {
            return false;
        }
        return boosterConfigs.getBoolean(KEY_LOCK_SCREEN_GUIDE, false);
    }*/

    public boolean getLockScreenOpened() {
        // TODO 判断是否有充电屏保开启
        return false;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @SuppressWarnings("deprecation")
    @SuppressLint("WorldReadableFiles")
    private static SharedPreferences getPackageSharedPreferences(Context context, String pkgName, String fileName) {
        if (!PackageUtils.isPkgInstalled(context, pkgName)) {
            return null;
        }

        int flags = Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE;
        try {
            Context packageContext = context.createPackageContext(pkgName, flags);
            int mode = Context.MODE_WORLD_READABLE | Context.MODE_MULTI_PROCESS;
            return packageContext.getSharedPreferences(fileName, mode);
        } catch (Throwable e) {
            if (FeatureConfig.DEBUG_LOG) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public String getSwitchConfigData() {
        SharedPreferences configs = getSharedPreferences();
        return configs.getString(SCREEN_SWITCH_CONFIG, "{}");
    }

    public void setSwitchConfigData(String data) {
        SharedPreferences configs = getSharedPreferences();
        configs.edit().putString(SCREEN_SWITCH_CONFIG, data).apply();
    }


    /**
     * 保存屏保卡片配置的FB广告ID
     */
    public void setScreenFbId(String fbid) {
        SharedPreferences configs = getSharedPreferences();
        configs.edit().putString(SP_SCREEN_FBID, fbid).apply();
    }

    /**
     * 获取屏保广告卡片交互方案配置
     */
    /*public MakingManager.AdStrategy getScreenAdStrategy() {
        SharedPreferences configs = getSharedPreferences();
        int strategy = configs.getInt(SP_SCREEN_STRATEGY, MakingConfigs.AD_STRATEGY_CLICK);
        return MakingManager.AdStrategy.findAdStrategy(strategy);
    }*/

    /**
     * 保存屏保广告卡片交互方案配置
     */
    public void setScreenAdStrategy(int strategy) {
        SharedPreferences configs = getSharedPreferences();
        configs.edit().putInt(SP_SCREEN_STRATEGY, strategy).apply();
    }

    /**
     * 是否屏保从来没有开启过或者关闭过
     */
    public boolean isLockScreenPure() {
        return true;
    }

    /**
     * 使用refer判断用户是否是organic用户.
     * 略认为有refer并且refer里面不包含organic的是买量用户
     */
    public static boolean notOrganicUser(Context context) {
        String refer = GlobalConfigSharedPrefManager.getReportedReferrer(context);
        return !TextUtils.isEmpty(refer) && !refer.contains("organic");
    }

    private static final String[] sGuideRefers = new String[]{
            "utm_source=com.dianxinos.dxbs&utm_medium=residual&pid=com.dianxinos.dxbs_residual",
            "utm_source=DuGroup&utm_medium=DuGroup&pid=DuGroupGroup",
            "utm_source=Grid&utm_medium=Grid&pid=Grid_Grid",
            "utm_source=com.dianxinos.dxbs&utm_medium=resultsdk&pid=com.dianxinos.dxbs&bdct=a",
            "utm_source=com.hm.coolermaster.cpucooler&utm_medium=resultsdk&pid=com.hm.coolermaster.cpucooler&bdct=a",
            "utm_source=com.hm.antivirus&utm_medium=resultsdk&pid=com.hm.antivirus&bdct=a"
    };

    public static boolean isGuideUser(Context context) {
        String refer = GlobalConfigSharedPrefManager.getReportedReferrer(context).trim();
        for (String str : sGuideRefers) {
            if (str.contains(refer)) {
                return true;
            }
        }
        return false;
    }
}
